

# class UserProfile(models.Model):
#     """
#     用户信息
#     """
#     name = models.CharField(u'姓名', max_length=32)
#     email = models.EmailField(u'邮箱')
#     phone = models.CharField(u'座机', max_length=32, null=True, blank=True)
#     mobile = models.CharField(u'手机', max_length=32)
#
#     class Meta:
#         verbose_name_plural = "用户表"
#
#     def __str__(self):
#         return self.name

from django.db import models
from django.contrib.auth.models import BaseUserManager,AbstractBaseUser,PermissionsMixin  #随后导入PermissionMixin
import django.utils.timezone as timezone


import django

## 使用 django 的用户认证。
class MyUserManager(BaseUserManager):
    def create_user(self, email, name,department ,password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            name=name,
            # roles=roles,
            department=department,
            #tel=tel,
            #memo=memo,

        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, name, department,password=None):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(  #更这里的 name = name
            email,
            name=name,
            department=department,

            # roles=roles,
            #department=department,
            #tel=tel,
            #memo=memo,
        )

        user.is_admin = True
        user.save(using=self._db)
        return user

class UserProfile(AbstractBaseUser,PermissionsMixin):
    email = models.EmailField( verbose_name='email address',max_length=255,unique=True,)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    ### 自己写的以下六行。
    name = models.CharField(max_length=32,verbose_name='email address')
    # token = models.CharField(u'token', max_length=128,default=None,blank=True,null=True)
    department = models.CharField(u'部门', max_length=32,default=None,blank=True,null=True)
    roles = models.ManyToManyField('Role',blank=True)
    tel = models.CharField(U'座机',max_length=32,default=None,blank=True,null=True)
    mobile = models.CharField(U'手机',max_length=32,default=None,blank=True,null=True)

    memo = models.TextField(U'备注',blank=True,null=True,default=None)
    date_joined = models.DateTimeField(blank=True,auto_now_add=True)

    ## 堡垒机相关。
    host_groups = models.ManyToManyField('HostGroups',verbose_name='授权主机组',blank=True)
    bind_hosts = models.ManyToManyField('BindHosts',verbose_name='授权主机',blank=True)
    valid_begin_time = models.DateTimeField(default=timezone.now,help_text="yyyy-mm-dd HH:MM:SS")
    valid_end_time = models.DateTimeField(blank=True,null=True,help_text="yyyy-mm-dd HH:MM:SS")
    # valid_begin_time = models.DateTimeField(default=django.utils.timezone.now)
    # valid_end_time = models.DateTimeField(blank=True,null=True)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    #REQUIRED_FIELDS = ['name'] #自己定义这里。
    # REQUIRED_FIELDS = ['name','department']

    REQUIRED_FIELDS = ['name','department']  # !! 通过控制这里，达到了python manage.py createsuperuser 时候添加部'department' 的功能。

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

    ## 自己添加定义以下这两行。
    class Meta:
         verbose_name = u'堡垒机用户信息'
         verbose_name_plural = u'堡垒机用户信息'

         permissions = (
            ('web_access_dashboard', '可以访问 审计主页'),
            ('web_batch_cmd_exec', '可以访问 批量命令执行页面'),
            ('web_batch_batch_file_transfer', '可以访问 批量文件分发页面'),
            ('web_config_center', '可以访问 堡垒机配置中心'),
            ('web_config_items', '可以访问 堡垒机各配置列表'),
            ('web_invoke_admin_action', '可以进行admin action执行动作'),
            ('web_table_change_page', '可以访问 堡垒机各配置项修改页'),
            ('web_table_change', '可以修改 堡垒机各配置项'),
        )

    def __unicode__(self):
        return self.name

#### 结合 CRM 系统的开发 #####
class Role(models.Model):
    """角色表"""
    name = models.CharField(unique=True,max_length=32)
    menus = models.ManyToManyField("Menu")

    def __str__(self):
        return self.name

class Menu(models.Model):
    """动态菜单"""
    name = models.CharField(unique=True,max_length=32)
    url_type = models.SmallIntegerField(choices=((0,'relative_name'),(1,'absolute_url')))
    url_name = models.CharField(unique=True,max_length=128)

    def __str__(self):
        return self.name

class Department(models.Model):
    name = models.CharField(max_length=64,unique=True)
    def __str__(self):
        return self.name
    class Meta:
        verbose_name = '部门'
        verbose_name_plural = '部门'

# class AdminInfo(models.Model):
#     """
#     用户登陆相关信息
#     """
#     user_info = models.OneToOneField("UserProfile")
#     username = models.CharField(u'用户名', max_length=64)
#     password = models.CharField(u'密码', max_length=64)
#
#     class Meta:
#         verbose_name_plural = "管理员表"
#
#     def __str__(self):
#         return self.user_info.name

class UserGroup(models.Model):
    """
    用户组
    """
    name = models.CharField(max_length=32, unique=True)
    users = models.ManyToManyField('UserProfile',related_name='U')

    class Meta:
        verbose_name_plural = "用户组表"

    def __str__(self):
        return self.name

class BusinessUnit(models.Model):
    """
    业务线
    """
    name = models.CharField('业务线', max_length=64, unique=True)
    contact = models.ForeignKey('UserGroup', verbose_name='业务联系人', related_name='c')
    manager = models.ForeignKey('UserGroup', verbose_name='系统管理员', related_name='m')

    class Meta:
        verbose_name_plural = "业务线表"

    def __str__(self):
        return self.name

class CPU(models.Model):

    asset = models.OneToOneField('Asset')
    cpu_model = models.CharField(u'CPU型号', max_length=128,blank=True)
    cpu_count = models.SmallIntegerField(u'物理cpu个数')
    cpu_core_count = models.SmallIntegerField(u'cpu核数')
    memo = models.TextField(u'备注', null=True,blank=True)
    create_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(blank=True,null=True)

    class Meta:
        verbose_name = 'CPU部件'
        verbose_name_plural = "CPU部件"
    def __str__(self):
        return self.cpu_model

class IDC(models.Model):
    """
    机房信息
    """
    name = models.CharField('机房', max_length=32)
    floor = models.IntegerField('楼层', null=True, blank=True, default=0)

    class Meta:
        verbose_name_plural = "机房表"

    def __str__(self):
        return self.name

class Tag(models.Model):
    """
    资产标签
    """
    name = models.CharField(verbose_name='标签', max_length=32, unique=True)

    class Meta:
        verbose_name_plural = "标签表"

    def __str__(self):
        return self.name

class ArticleDetail(models.Model):
    article = models.OneToOneField('Asset')
    # nid = models.BigAutoField(primary_key=True)
    title = models.CharField(verbose_name='文章标题', max_length=128)
    summary = models.CharField(verbose_name='文章简介', max_length=255)
    content = models.TextField(verbose_name='文章内容', )

    class Meta:
        verbose_name_plural = '备注_文章'

    def __str__(self):
        return ('%s----%s') % (self.id,self.title)

class Asset(models.Model):
    """
    资产信息表，所有资产公共信息（交换机，服务器，防火墙等）
    """
    device_type_choices = (
        (1, '服务器-硬件'),
        (2, '服务器-虚拟机'),
        (3, '交换机'),
        (4, '防火墙'),
    )
    device_status_choices = (
        (1, '上架'),
        (2, '在线'),
        (3, '离线'),
        (4, '下架'),
    )

    device_type_id = models.IntegerField(verbose_name="资产类型", choices=device_type_choices, default=1)
    name = models.CharField(max_length=64,unique=True)
    device_status_id = models.IntegerField(verbose_name="资产状态", choices=device_status_choices, default=1)

    cabinet_num = models.CharField(verbose_name='机柜号', max_length=30, null=True, )
    cabinet_order = models.CharField(verbose_name='机柜中序号', max_length=30, null=True, )

    sn = models.CharField(u'资产SN号',max_length=128, unique=True)
    idc = models.ForeignKey('IDC', verbose_name='IDC机房', null=True,blank=True ,  default=None)
    business_unit = models.ForeignKey('BusinessUnit', verbose_name='属于的业务线', null=True,blank=True ,default=None)

    contract = models.ForeignKey('Contract', verbose_name=u'合同',null=True, blank=True)
    trade_date = models.DateField(u'购买时间',null=True, blank=True)
    expire_date = models.DateField(u'过保修期',null=True, blank=True)
    price = models.FloatField(u'价格',null=True, blank=True)


    tag = models.ManyToManyField('Tag')
    manufactory = models.ForeignKey('Manufactory',verbose_name=u'制造商',null=True, blank=True)

    latest_date = models.DateField(verbose_name="最后更新时间", null=True)
    create_at = models.DateTimeField(auto_now_add=True, null=True )

    class Meta:
        verbose_name_plural = "资产表"


    def __str__(self):
        # return "%s-%s-%s" % (self.id, self.idc.name, self.cabinet_num)
        return "%s--%s" % (self.id,self.name)



class Server(models.Model):
    """
    服务器信息 && 堡垒机hosts主机表。
    """
    asset = models.OneToOneField('Asset')

    hostname = models.CharField(max_length=128, unique=True)                                         # 堡垒机
    sn = models.CharField('SN号', max_length=64, db_index=True, null=True, blank=True)
    # manufacturer = models.CharField(verbose_name='制造商', max_length=64, null=True, blank=True)

    model = models.CharField('型号', max_length=64, null=True, blank=True)

    # Remote_login_user = models.ForeignKey('RemoteUser',related_name='Remote_login_user')
    # password = models.ForeignKey('RemoteUser',related_name='Remoteuser_password')

    manage_ip = models.GenericIPAddressField('管理IP',null=True,blank=True)
    private_ip = models.GenericIPAddressField('私有IP',null=True, blank=True )                       # 堡垒机
    public_ip = models.GenericIPAddressField('公网IP', null=True, blank=True )

    port = models.PositiveIntegerField(default=22)                                                   #堡垒机
    idc = models.ForeignKey("IDC")                                                                   # 堡垒机
    enabled = models.BooleanField(default=True)                                                      # 堡垒机

    os_platform = models.CharField('系统', max_length=64, null=True, blank=True)
    os_version = models.CharField('系统版本', max_length=64, null=True, blank=True)

    cpu_count = models.IntegerField('CPU个数', null=True, blank=True)
    cpu_physical_count = models.IntegerField('CPU物理个数', null=True, blank=True)
    cpu_model = models.CharField('CPU型号', max_length=128, null=True, blank=True)

    raid_type = models.CharField(u'raid类型',max_length=512, blank=True,null=True)
    # os_type  = models.CharField(u'操作系统类型',max_length=64, blank=True,null=True)
    # os_distribution =models.CharField(u'发型版本',max_length=64, blank=True,null=True)
    # os_release  = models.CharField(u'操作系统版本',max_length=64, blank=True,null=True)

    create_at = models.DateTimeField(auto_now_add=True)   # CMDB && 堡垒机

    class Meta:
        verbose_name_plural = "服务器表"
        verbose_name = "服务器"

    def __str__(self):
        return '%s--%s--%s' % (self.id, self.hostname,self.private_ip)

class NetworkDevice(models.Model):
    asset = models.OneToOneField('Asset')
    management_ip = models.CharField('公网IP', max_length=64, blank=True, null=True)
    vlan_ip = models.CharField('VlanIP', max_length=64, blank=True, null=True)

    intranet_ip = models.CharField('内网IP', max_length=128, blank=True, null=True)
    sn = models.CharField('SN号', max_length=64, unique=True)
    manufacture = models.CharField(verbose_name=u'制造商', max_length=128, null=True, blank=True)
    model = models.CharField('型号', max_length=128, null=True, blank=True)
    port_num = models.SmallIntegerField('端口个数', null=True, blank=True)
    device_detail = models.CharField('设置详细配置', max_length=255, null=True, blank=True)

    name = models.CharField(u'网卡名', max_length=64, blank=True,null=True)
    macaddress = models.CharField(u'MAC', max_length=64,unique=True)

    # ipaddress = models.GenericIPAddressField(u'IP', blank=True,null=True)

    netmask = models.CharField(max_length=64,blank=True,null=True)
    bonding = models.CharField(max_length=64,blank=True,null=True)
    memo = models.CharField(u'备注',max_length=128, blank=True,null=True)
    create_date = models.DateTimeField(blank=True, auto_now_add=True)
    update_date = models.DateTimeField(blank=True,null=True)

    class Meta:
        verbose_name_plural = "网络设备"

class Disk(models.Model):
    """
    硬盘信息
    """
    asset = models.ForeignKey('Asset')
    server_obj = models.ForeignKey('Server',related_name='disk')
    slot = models.CharField('插槽位', max_length=8)
    model = models.CharField('磁盘型号', max_length=128)
    capacity = models.FloatField('磁盘容量GB')
    pd_type = models.CharField('磁盘类型', max_length=64)

    class Meta:
        verbose_name_plural = "硬盘表"

    def __str__(self):
        return self.slot

class NIC(models.Model):
    """
    网卡信息
    """
    asset = models.ForeignKey('Asset')
    name = models.CharField('网卡名称', max_length=128)
    hwaddr = models.CharField('网卡mac地址', max_length=64)
    netmask = models.CharField('掩码',max_length=64)
    ipaddrs = models.CharField('ip地址', max_length=256)
    up = models.BooleanField('状态',default=False)
    server_obj = models.ForeignKey('Server',related_name='nic')

    class Meta:
        verbose_name_plural = "网卡表"

    def __str__(self):
        return self.name

class Memory(models.Model):
    """
    内存信息
    """
    asset = models.ForeignKey('Asset')
    # server_obj = models.ForeignKey('Server',related_name='memory')

    sn = models.CharField(u'SN号', max_length=128, blank=True,null=True)
    model =  models.CharField(u'内存型号', max_length=128)
    slot = models.CharField(u'插槽', max_length=64)
    capacity = models.IntegerField(u'内存大小(MB)')
    memo = models.CharField(u'备注',max_length=128, blank=True,null=True)

    speed = models.CharField('速度', max_length=16, null=True, blank=True)
    manufacturer = models.CharField('制造商', max_length=32, null=True, blank=True)

    create_date = models.DateTimeField(blank=True, auto_now_add=True)
    update_date = models.DateTimeField(blank=True,null=True)

    def __str__(self):
        return '%s:%s:%s' % (self.asset_id,self.slot,self.capacity)

    class Meta:
        verbose_name = '内存'
        verbose_name_plural = "内存表"
    #     unique_together = ("asset", "slot")
    # auto_create_fields = ['sn','slot','model','capacity']

class AssetRecord(models.Model):
    """
    资产变更记录,creator为空时，表示是资产汇报的数据。
    """
    asset_obj = models.ForeignKey('Asset', related_name='ar')
    content = models.TextField(null=True)
    creator = models.ForeignKey('UserProfile', null=True, blank=True)
    create_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = "资产记录表"

    def __str__(self):
        return "%s-%s-%s" % (self.asset_obj.idc.name, self.asset_obj.cabinet_num, self.asset_obj.cabinet_order)

class ErrorLog(models.Model):
    """
    错误日志,如：agent采集数据错误 或 运行错误
    """
    asset_obj = models.ForeignKey('Asset', null=True, blank=True)
    title = models.CharField(max_length=16)
    content = models.TextField()
    create_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = "错误日志表"

    def __str__(self):
        return self.title

class Manufactory(models.Model):

    manufactory = models.CharField(u'厂商',max_length=64, unique=True)
    
    support_num = models.CharField(u'支持电话',max_length=30,blank=True)
    memo = models.CharField(u'备注',max_length=128,blank=True)

    def __str__(self):
        return self.manufactory
    class Meta:
        verbose_name = '厂商'
        verbose_name_plural = "厂商"

class Contract(models.Model):
    '''
    合同表。可进行合同管理。
    '''
    sn = models.CharField(u'合同号', max_length=128,unique=True)
    name = models.CharField(u'合同名称', max_length=64 )
    memo = models.TextField(u'备注', blank=True,null=True)
    price = models.IntegerField(u'合同金额')
    detail = models.TextField(u'合同详细',blank=True,null=True)
    start_date = models.DateField(blank=True)
    end_date = models.DateField(blank=True)
    license_num = models.IntegerField(u'license数量',blank=True)

    create_date = models.DateField(auto_now_add=True)
    update_date= models.DateField(auto_now=True)

    class Meta:
        verbose_name = '合同'
        verbose_name_plural = "合同"

    def __str__(self):
        return self.name

class NewAssetApprovalZone(models.Model):
    '''
    资产待批准表
    '''
    sn = models.CharField(u'资产SN号',max_length=128, unique=True)
    asset_type_choices = (
        ('server', u'服务器'),
        ('switch', u'交换机'),
        ('router', u'路由器'),
        ('firewall', u'防火墙'),
        ('storage', u'存储设备'),
        ('NLB', u'NetScaler'),
        ('wireless', u'无线AP'),
        ('software', u'软件资产'),
        ('others', u'其它类'),
    )
    asset_type = models.CharField(choices=asset_type_choices,max_length=64,blank=True,null=True)
    manufactory = models.CharField(max_length=64,blank=True,null=True)
    model = models.CharField(max_length=128,blank=True,null=True)
    ram_size = models.IntegerField(blank=True,null=True)
    cpu_model = models.CharField(max_length=128,blank=True,null=True)
    cpu_count = models.IntegerField(blank=True,null=True)
    cpu_core_count = models.IntegerField(blank=True,null=True)
    os_distribution =  models.CharField(max_length=64,blank=True,null=True)
    os_type =  models.CharField(max_length=64,blank=True,null=True)
    os_release =  models.CharField(max_length=64,blank=True,null=True)
    data = models.TextField(u'资产数据')
    date = models.DateTimeField(u'汇报日期',auto_now_add=True)
    approved = models.BooleanField(u'已批准',default=False)
    approved_by = models.ForeignKey('UserProfile',verbose_name=u'批准人',blank=True,null=True,)
    approved_date = models.DateTimeField(u'批准日期',blank=True,null=True)

    def __str__(self):
        return '%s--%s' %  (self.id,self.sn)

    class Meta:
        verbose_name = '新上线待批准资产'
        verbose_name_plural = "新上线待批准资产"


########### 堡垒机表 ##############
# class Host(models.Model):
#     """存储所有主机"""
#     hostname = models.CharField(max_length=64)
#     ip_addr = models.GenericIPAddressField(unique=True)
#     port = models.PositiveSmallIntegerField(default=22)
#     idc = models.ForeignKey("IDC")
#
#     enabled = models.BooleanField(default=True)
#
#     def __str__(self):
#         return self.ip_addr


class HostGroups(models.Model):
    """主机组"""
    name = models.CharField(max_length=64, unique=True)
    bind_hosts  = models.ManyToManyField("BindHosts",blank=True)

    memo = models.CharField(max_length=128,blank=True,null=True,verbose_name='备注')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '主机组'
        verbose_name_plural = '主机组'

# class RemoteUser(models.Model):
#     """存储远程用户名密码"""
#     username = models.CharField(max_length=64)
#     password = models.CharField(max_length=128,blank=True,null=True,help_text='如果auth_method选择的是SSH/KEY,那此处不需要填写..')
#
#     auth_type_choices = ((0,'ssh/password'),(1,'ssh/key'))
#     auth_type = models.SmallIntegerField(choices=auth_type_choices,default=0,help_text='如果选择SSH/KEY，请确保你的私钥文件已在settings.py中指定')
#     #hosts = models.ManyToManyField("Host")
#     memo = models.CharField(max_length=128,blank=True,null=True,verbose_name='备注')
#
#     def __str__(self):
#         return "%s(%s)%s" %( self.username,self.get_auth_type_display(),self.password)
#
#     class Meta:
#         verbose_name = '远程用户'
#         verbose_name_plural = '远程用户'
#         unique_together = ('username','auth_type','password')

class BindHosts(models.Model):
    """绑定远程主机和远程用户的对应关系"""

    host = models.ForeignKey("Server")
    remote_user = models.CharField(max_length=64)
    password = models.CharField(max_length=128,blank=True,null=True,help_text='如果auth_method选择的是SSH/KEY,那此处不需要填写..')

    auth_type_choices = ((0,'ssh/password'),(1,'ssh/key'))
    auth_type = models.SmallIntegerField(choices=auth_type_choices,default=0,help_text='如果选择SSH/KEY，请确保你的私钥文件已在settings.py中指定')
    memo = models.CharField(max_length=128,blank=True,null=True,verbose_name='备注')
    enabled = models.BooleanField(default=True)

    def __str__(self):
        return "%s-%s(%s)" % ( self.host.hostname,self.remote_user, self.get_auth_type_display())

    class Meta:
        unique_together = ("host", "remote_user")
        verbose_name = '主机与远程用户绑定'
        verbose_name_plural = '主机与远程用户绑定'

# class Session(models.Model):
#     '''生成用户操作 session[会话] id '''
#     user = models.ForeignKey('UserProfile')
#     bind_host = models.ForeignKey('BindHosts')
#     tag = models.CharField(max_length=128,default='n/a')
#     closed = models.BooleanField(default=False)
#     cmd_count = models.IntegerField(default=0)    #命令执行数量
#     stay_time = models.IntegerField(default=0, help_text="每次刷新自动计算停留时间",verbose_name="停留时长(seconds)")
#     date = models.DateTimeField(auto_now_add=True)
#
#     def __str__(self):
#         return '<id:%s user:%s bind_host:%s>' % (self.id,self.user.email,self.bind_host.host)
#     class Meta:
#         verbose_name = '审计日志new'
#         verbose_name_plural = '审计日志new'

class SessionTrack(models.Model):
    '''生成用户操作session id '''
    user = models.ForeignKey('UserProfile',verbose_name='堡垒机账户')
    bind_host = models.ForeignKey('BindHosts',verbose_name='登录主机')
    cmd_count = models.IntegerField(default=0,verbose_name='命令数')  # 命令执行数量
    stay_time = models.IntegerField(default=0, help_text="每次刷新自动计算停留时间", verbose_name="停留时长(seconds)")
    date = models.DateTimeField(auto_now_add=True,verbose_name='登录时间') # 会话开始时间,
    closed = models.BooleanField(default=False)  # 会话是否关闭

    def __str__(self):
        return '%s-%s' % (self.id,self.user.name)
    class Meta:
        verbose_name = u'用户登录session表'
        verbose_name_plural = u'用户登录session表'

class AuditLog(models.Model):
    session = models.ForeignKey('SessionTrack')  # 关联到一个 ssh's session会话。
    user = models.ForeignKey('UserProfile')
    host = models.ForeignKey('BindHosts')
    action_choices = (
        (0,'CMD'),
        (1,'Login'),
        (2,'Logout'),
        (3,'GetFile'),
        (4,'SendFile'),
        (5,'exception'),
    )
    action_type = models.IntegerField(choices=action_choices,default=0)
    cmd = models.TextField()
    memo = models.CharField(max_length=128,blank=True,null=True)
    date = models.DateTimeField(auto_now_add=True,verbose_name='命令执行时间')

    def __str__(self):
        return '%s-->%s@%s:%s' % (self.user.name, self.host.remote_user, self.host.host.manage_ip, self.cmd)

    class Meta:
        verbose_name = u'审计日志'
        verbose_name_plural = u'审计日志'


class Task(models.Model):
    """批量任务记录表"""

    user = models.ForeignKey("UserProfile")
    hosts = models.ManyToManyField('BindHosts')

    start_time = models.DateTimeField(auto_now_add=True)
    end_time = models.DateTimeField(null=True,blank=True)

    task_type_choices = ((0,"CMD"),(1,"批量发送文件"),(3,"批量下载文件"))
    task_type = models.CharField(choices=task_type_choices,max_length=50)

    files_dir = models.CharField("文件上传临时目录",blank=True,null=True,max_length=32)

    cmd = models.TextField(verbose_name="任务内容")
    #hosts = models.ManyToManyField("BindHost")
    date  = models.DateTimeField(auto_now_add=True)

    expire_time = models.IntegerField(default=30)
    task_pid = models.IntegerField(default=0)
    note = models.CharField(max_length=100,blank=True,null=True)

    def __str__(self):
        return "%s %s" %(self.task_type,self.cmd)

    class Meta:
        verbose_name = '批量任务'
        verbose_name_plural = '批量任务'

class TaskLogDetail(models.Model):
    """" 任务返回--日志记录 """
    child_of_task = models.ForeignKey('Task')
    bind_host = models.ForeignKey("BindHosts")
    event_log = models.TextField()


    result_choices= (('success','Success'),('failed','Failed'),('init','Init'))
    result = models.CharField(choices=result_choices,max_length=30,default='init')

    start_date = models.DateTimeField(auto_now_add=True)
    end_date = models.DateTimeField(auto_now_add=True,blank=True,null=True)

    note = models.CharField(max_length=100,blank=True)


    def __str__(self):
        return "child of:%s result:%s" %(self.child_of_task.id, self.result)
    class Meta:
        verbose_name = '批量任务日志'
        verbose_name_plural = '批量任务日志'

class Token(models.Model):
    """
     登录的token值。
    """
    user = models.ForeignKey('UserProfile')
    host = models.ForeignKey('BindHosts')
    token = models.CharField(max_length=64)
    date = models.DateTimeField(default=django.utils.timezone.now)
    expire = models.IntegerField(default=300)

    def __str__(self):
        return '%s : %s' %(self.host.host.private_ip,self.token)












